package com.security.learn01.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author llj
 * @create 2022-06-26 21:27
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private FailureHandle failureHandle;
    @Autowired
    private SuccessHandle successHandle;

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/hello").permitAll()
                .antMatchers("/index").hasRole("User")
                .antMatchers("/loginTest").hasRole("Admin")
                //权限认证处理页面(先是异常处理，这个地方就是处理无权限的问题)
                .and().exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
        //没有权限会默认跳到登录页面，需要开启登录页面
        http.formLogin().successHandler(successHandle).failureHandler(failureHandle);
        //防止网站攻击，get,post
        http.csrf().disable();//关闭csrf功能，登出失败存在的原因
        //注销，开启注销功能，跳转首页
        //http.logout().logoutSuccessUrl("/index");

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("User")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("user").password(new BCryptPasswordEncoder().encode("admin")).roles("Admin");
    }
}
